package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.Md5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业务实现类：员工
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void add(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Pwd);
        employee.setSalt(salt);

        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.add(logininfo);
        employee.setLogininfoId(logininfo.getId());
        super.add(employee);
        employeeMapper.addEmployeeAndRole(employee);
    }

    public Logininfo employee2Logininfo(Employee employee){
        Logininfo logininfo = new Logininfo();

        BeanUtils.copyProperties(employee,logininfo);
        //当前对象是店铺管理员
        logininfo.setType(0);
        return logininfo;
    }

    @Override
    public void delete(Long id) {
        Employee employee = employeeMapper.findById(id);
        logininfoMapper.delete(employee.getLogininfoId());
        employeeMapper.deleteEmployeeAndRole(employee.getId());
        super.delete(id);
    }

    @Override
    public void update(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Pwd);

        Logininfo logininfo = employee2Logininfo(employee);
        Long logininfo_id = employeeMapper.findById(employee.getId()).getLogininfoId();
        logininfo.setId(logininfo_id);

        logininfoMapper.update(logininfo);
        //登录信息id和店铺信息id不能修改
        employeeMapper.deleteEmployeeAndRole(employee.getId());
        super.update(employee);
    }


    @Override
    public void batchDelete(List<Long> ids) {
        for (Long id : ids) {
            delete(id);
        }
    }

    @Override
    public List<Employee> findByShopId(Long id) {
        return employeeMapper.findByShopId(id);
    }
}
